package com.legal.utils;

import lombok.Getter;
import lombok.Setter;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "tess4j")
public class Tess4jUtil {

    private String language;

    public String doOCR(BufferedImage image) throws TesseractException {
        ITesseract tesseract = new Tesseract();
        String realDataPath = null;
        try {
            realDataPath = getRealTessDataPath();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        tesseract.setDatapath(realDataPath);
        tesseract.setLanguage(language);

        String result = tesseract.doOCR(image);
        return result.replaceAll("\\r|\\n", "-").replaceAll(" ", "");
    }

    private String getRealTessDataPath() throws IOException {
        // 1. 尝试从classpath获取资源
        ClassPathResource resource = new ClassPathResource("tessdata");

        // 开发环境 - 直接使用文件系统路径
        if (resource.exists()) {
            File file = resource.getFile();
            if (file.isDirectory()) {
                return file.getAbsolutePath();
            }
            return file.getParentFile().getAbsolutePath();
        }

        // 2. 打包环境 - 提取到临时目录
        Path tempDir = Files.createTempDirectory("tessdata-");
        extractTessDataToTemp(tempDir);

        // 设置权限（Linux系统可能需要）
        if (!System.getProperty("os.name").toLowerCase().contains("win")) {
            tempDir.toFile().setReadable(true, false);
            tempDir.toFile().setExecutable(true, false);
        }

        return tempDir.toAbsolutePath().toString();
    }

    private void extractTessDataToTemp(Path tempDir) throws IOException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath:tessdata/*.traineddata");

        if (resources.length == 0) {
            throw new IOException("No traineddata files found in classpath:tessdata/");
        }

        for (Resource res : resources) {
            Path target = tempDir.resolve(res.getFilename());
            Files.copy(res.getInputStream(), target, StandardCopyOption.REPLACE_EXISTING);
        }
    }
}